package avicit.bdp.dms.das.rest;

import avicit.bdp.common.utils.enums.StatusEnums;
import avicit.bdp.core.constant.Constants;
import avicit.bdp.dms.das.dto.BdpDasCategoryDTO;
import avicit.bdp.dms.das.service.BdpDasCategoryService;
import avicit.platform6.api.system.ConvertColumnClient;
import avicit.platform6.api.system.impl.SystemConstant;
import avicit.platform6.commons.utils.BusinessUtil;
import avicit.platform6.core.context.ThreadContextHelper;
import avicit.platform6.core.rest.msg.QueryRespBean;
import avicit.platform6.core.rest.msg.ResponseMsg;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import springfox.documentation.annotations.ApiIgnore;

import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;


/**
 * 数据模型分类Rest接口
 */
@RestController
@Api(tags = "数据模型分类Rest接口")
@RequestMapping("/api/bdp/dms/das/category")
public class BdpDasCategoryRest {

    @Autowired
    private BdpDasCategoryService bdpDasCategoryService;

    @Autowired
    private ConvertColumnClient convertColumnClient;

    private static final Logger LOGGER = LoggerFactory.getLogger(BdpDasCategoryRest.class);

    /**
     * 新建数据模型分类对象
     */
    @ApiOperation(value = "新增对象")
    @PostMapping("/insertCategory")
    public ResponseMsg<String> insertCategory(@RequestBody BdpDasCategoryDTO bdpDasCategory) {
        ResponseMsg<String> responseMsg = new ResponseMsg<>();
        bdpDasCategory.setOrgIdentity(ThreadContextHelper.getOrgId());
        responseMsg.setResponseBody(bdpDasCategoryService.insertBdpDasCategory(bdpDasCategory));
        return responseMsg;
    }

    /**
     * 修改数据模型分类对象
     */
    @ApiOperation(value = "修改对象")
    @PostMapping("/updateCategory")
    public ResponseMsg<String> updateCategory(@RequestBody BdpDasCategoryDTO bdpDasCategory) {
        LOGGER.debug("保存分类对象参数={}：", bdpDasCategory);
        ResponseMsg<String> responseMsg = new ResponseMsg<>();
        bdpDasCategoryService.updateBdpDasCategory(bdpDasCategory);
        return responseMsg;
    }


    /**
     * 删除数据模型分类对象
     */
    @ApiOperation(value = "按主键单条删除")
    @ApiParam(value = "主键id", name = "id", required = true)
    @DeleteMapping
    public ResponseMsg<Integer> deleteById(@RequestBody String id) {
        ResponseMsg<Integer> responseMsg = new ResponseMsg<>();
        bdpDasCategoryService.deleteBdpDasCategoryById(id);
        return responseMsg;
    }

    /**
     * 查询树结构（进行权限过滤）
     */
    @ApiOperation(value = "查询树结构")
    @GetMapping("/findCategoryList")
    public ResponseMsg<List<BdpDasCategoryDTO>> findCategoryList() {
        ResponseMsg<List<BdpDasCategoryDTO>> responseMsg = new ResponseMsg<>();
        List<BdpDasCategoryDTO> result = bdpDasCategoryService.findCategoryList();
        valueConvert(result);
        responseMsg.setResponseBody(result);
        return responseMsg;
    }

    /**
     * 查询树结构
     */
    @ApiOperation(value = "查询树结构")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "角色Id", dataType = "String", required = true),
            @ApiImplicitParam(name = "keyWords", value = "查询关键字", dataType = "String")
    })
    @GetMapping("/getAllCategory")
    public ResponseMsg<List<BdpDasCategoryDTO>> getAllCategory(
            @RequestParam String roleId,
            @RequestParam(required = false) String keyWords) {
        ResponseMsg<List<BdpDasCategoryDTO>> responseMsg = new ResponseMsg<>();
        List<BdpDasCategoryDTO> result = bdpDasCategoryService.getAllCategory(roleId, keyWords);
        valueConvert(result);
        responseMsg.setResponseBody(result);
        return responseMsg;
    }


    @ApiOperation(value = "无权限过滤查询树结构")
    @GetMapping("/findCategoryTree")
    public ResponseMsg<List<BdpDasCategoryDTO>> findCategoryTree() {
        ResponseMsg<List<BdpDasCategoryDTO>> responseMsg = new ResponseMsg<>();
        List<BdpDasCategoryDTO> result = bdpDasCategoryService.findCategoryTree();
        valueConvert(result);
        responseMsg.setResponseBody(result);
        return responseMsg;
    }

    @ApiOperation(value = "无权限过滤查询启用状态的树结构")
    @GetMapping("/findCategoryTreeByStatus")
    public ResponseMsg<List<BdpDasCategoryDTO>> findCategoryTreeByStatus() {
        ResponseMsg<List<BdpDasCategoryDTO>> responseMsg = new ResponseMsg<>();
        List<BdpDasCategoryDTO> result = bdpDasCategoryService.findCategoryTreeByStatus();
        valueConvert(result);
        responseMsg.setResponseBody(result);
        return responseMsg;
    }


    @ApiOperation(value = "根据主题id查询下一级主题")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "关键词", name = "keyWords", dataType = "String"),
            @ApiImplicitParam(value = "主题id", name = "categoryId", dataType = "String"),
            @ApiImplicitParam(value = "当前页", name = "pageNo", dataType = "Int"),
            @ApiImplicitParam(value = "每页大小", name = "pageSize", dataType = "Int")
    })
    @GetMapping("/findCategoryDataList")
    public ResponseMsg<QueryRespBean<BdpDasCategoryDTO>> findCategoryDataList(
            @RequestParam(required = false) String keyWords,
            @RequestParam String categoryId,
            @RequestParam(defaultValue = "1", required = false) Integer pageNo,
            @RequestParam(defaultValue = "10", required = false) Integer pageSize) {

        ResponseMsg<QueryRespBean<BdpDasCategoryDTO>> responseMsg = new ResponseMsg<>();
        QueryRespBean<BdpDasCategoryDTO> queryRespBean =
                bdpDasCategoryService.findCategoryDataList(categoryId,keyWords, pageNo, pageSize);
        valueConvert(queryRespBean.getResult());
        responseMsg.setResponseBody(queryRespBean);
        return responseMsg;
    }

    @ApiOperation(value = "启用/停用")
    @PostMapping("/updateStatus")
    public ResponseMsg<Boolean> updateStatus(@RequestBody BdpDasCategoryDTO bdpDasCategoryDTO) {
        ResponseMsg<Boolean> responseMsg = new ResponseMsg<>();
        bdpDasCategoryService.updateStatus(bdpDasCategoryDTO.getId(), bdpDasCategoryDTO.getStatus(),
                bdpDasCategoryDTO.getLowerNode());
        return responseMsg;
    }

    /**
     * 判断分类名称是否重复（同一层级）
     */
    @ApiOperation(value = "判断分类名称是否重复（同一层级）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "categoryId", value = "分类id", dataType = "String", paramType = "body", required = true),
            @ApiImplicitParam(name = "categoryName", value = "分类名称", dataType = "String", paramType = "body", required = true),
            @ApiImplicitParam(name = "parentId", value = "分类父id", dataType = "String", paramType = "body", required = true)
    })
    @PostMapping("/isSameName")
    public ResponseMsg<Integer> isSameName(@ApiIgnore @RequestBody Map<String, String> qureyMap) {
        ResponseMsg<Integer> responseMsg = new ResponseMsg<>();
        String categoryId = MapUtils.getString(qureyMap, "categoryId", "");
        String categoryName = MapUtils.getString(qureyMap, "categoryName", "");
        String parentId = MapUtils.getString(qureyMap, "parentId", "");
        Integer flag = bdpDasCategoryService.isSameName(categoryId, categoryName, parentId);
        responseMsg.setResponseBody(flag);
        return responseMsg;
    }

    /**
     * 判断分类code是否重复
     */
    @ApiOperation(value = "判断分类code是否重复")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "categoryId", value = "分类id", dataType = "String", paramType = "body", required = true),
            @ApiImplicitParam(name = "categoryCode", value = "分类code", dataType = "String", paramType = "body", required = true)
    })
    @PostMapping("/isSameCode")
    public ResponseMsg<Integer> isSameCode(@ApiIgnore @RequestBody Map qureyMap) {
        ResponseMsg<Integer> responseMsg = new ResponseMsg<>();
        String categoryId = MapUtils.getString(qureyMap, "categoryId", "");
        String categoryCode = MapUtils.getString(qureyMap, "categoryCode", "");
        Integer flag = bdpDasCategoryService.isSameCode(categoryId, categoryCode);
        responseMsg.setResponseBody(flag);
        return responseMsg;
    }

    /**
     * 通过平台API将字段值转换为名称，包括通用选择组件、通用代码
     */
    private void valueConvert(List<BdpDasCategoryDTO> bdpDasCategoryDTOList) {
        //循环组装请求数据
        Map<String, Set<String>> convertFormData = new HashMap<>();
        for (BdpDasCategoryDTO bdpDasCategoryDTO : bdpDasCategoryDTOList) {
            BusinessUtil.createConvertSet(convertFormData, SystemConstant.USER, bdpDasCategoryDTO.getCreatedBy());
            BusinessUtil.createConvertSet(convertFormData, Constants.BDP_DATA_SECRET_LEVEL_KEY, bdpDasCategoryDTO.getSecretLevel());
        }
        if (convertFormData.size() > 0) {
            //获取请求结果
            Map<String, Map<String, String>> convertResultData = convertColumnClient.replace(convertFormData);
            //循环设置Alias或Name的值
            for (BdpDasCategoryDTO bdpDasCategory : bdpDasCategoryDTOList) {
                bdpDasCategory.setStatusString(StatusEnums.getDescByCode(bdpDasCategory.getStatus()));
                bdpDasCategory.setCreatedBy(BusinessUtil.convertFormat(convertResultData, SystemConstant.USER,
                        bdpDasCategory.getCreatedBy()));
                bdpDasCategory.setSecretLevelName(BusinessUtil.convertFormat(
                        convertResultData, Constants.BDP_DATA_SECRET_LEVEL_KEY, bdpDasCategory.getSecretLevel()));
            }
        }
    }

    @ApiOperation(value = "获取当前最大排序整数")
    @ApiImplicitParam(name = "categoryId", value = "分类id", dataType = "String", required = true)
    @GetMapping("/getMaxOrder")
    public ResponseMsg<Integer> getMaxOrder(@RequestParam String categoryId) {
        ResponseMsg<Integer> responseMsg = new ResponseMsg<>();
        Integer flag = bdpDasCategoryService.getMaxOrder(categoryId);
        responseMsg.setResponseBody(flag);
        return responseMsg;
    }

    @ApiOperation(value = "通过ID查询")
    @ApiParam(value = "id", name = "id", required = true)
    @GetMapping("/{id}")
    public ResponseMsg<BdpDasCategoryDTO> queryById(@PathVariable String id) {
        ResponseMsg<BdpDasCategoryDTO> responseMsg = new ResponseMsg<>();
        responseMsg.setResponseBody(bdpDasCategoryService.queryById(id));
        return responseMsg;
    }
}
